'use strict'

const Koa = require('koa')
const favicon = require('koa-favicon')
const conditional = require('koa-conditional-get')
const etag = require('koa-etag')
const bodyparser = require('koa-bodyparser')
const json = require('koa-json')

const router = require('./routes')
const middle = require('./middlewares')
const extend = require('./lib/koa-extend')

const app = new Koa()

// App Setting
app.proxy = true

// Extend Koa Context
Object.assign(app.context, extend)

// Middleware
app.use(favicon('public/favicon.ico'))
app.use(middle.error)
app.use(conditional())
app.use(etag())
app.use(bodyparser())
app.use(json())
app.use(middle.cors)
app.use(router.routes())
app.use(router.allowedMethods())

// 404
app.use(async ctx => {
    if (ctx.status === 404) {
        ctx.throw(404, 'API_NOT_FOUND')
    }
})

module.exports = app